var PATH = require("path"),
    svn = require("./lib/svn"),
    FS = require("fs"),
    fs = require("./lib/fs");

var pkg = JSON.parse(FS.readFileSync(process.argv[2]));
if(!pkg) {
    return;
}

var tmpDir = "tmp",
    trunkDir = PATH.join(tmpDir, "trunk"),
    releaseDir = PATH.join(tmpDir, "release");

function build(src, target) {
    var fileButter = FS.readFileSync(src);
    fileButter += "\r\nbuild at " + (new Date());
    FS.writeFileSync(target, fileButter);
    console.log("succeed : build file " + src);
}

svn.isAvailable().then(function() {
    if(FS.existsSync(tmpDir)) {
        fs.rm(tmpDir);
        console.log("succeed : clean dir " + tmpDir);
    }
    FS.mkdirSync(tmpDir);

}).then(function() {
    return svn.checkout(pkg.devInfo.trunk, trunkDir);

}).then(function() {
    return svn.checkout(pkg.devInfo.release, releaseDir);

}).then(function() {
    FS.readdirSync(releaseDir).forEach(function(path) {
        if(path !== ".svn") {
            path = PATH.join(releaseDir, path);
            fs.rm(path);
        }
    });
    console.log("succeed : clean local dir " + releaseDir);

}).then(function() {
    build(PATH.join(trunkDir, "app.js"), PATH.join(releaseDir, "app.min.js"));

}).then(function() {
    return svn.stat(releaseDir).then(function(data) {
        var news = [];
        data.forEach(function(rec) {
            if(/^\?/.test(rec)) {
                news.push(rec.substr(rec.lastIndexOf(" ") + 1));
            }
        });
        return news;
    });

}).then(function(news) {
    if(news.length > 0) {
        svn.add(news.join(" "));
    }

}).then(function() {
    return svn.commit(releaseDir, "test commit");

}).then(function() {
    return svn.copy(releaseDir, pkg.devInfo.tags + "/" + (+new Date()));

}).then(function() {
    console.log("succeed : build project " + pkg.name);

});